<template>
  <div class="app-container" v-loading="loading">
    <u-page-config
      :filter-array="filterArray"
      v-model="filter"
      :actionBtn="actionBtn"
      label-width="100px"
      :getList="getList"
      :tableData="tableData"
      :tableColumn="tableColumn"
      :total="total"
      :loading="loading"
      :selectable="selectableFn"
      showSelection
      @handleSelectionChange="handleSelectionChange"
      @addPlan="addPlan"
      @stopPlan="stopPlan"
      @rowDetail="rowDetail"
    >

      <template #deviceStatus="scope">
        <dict-tag
          :options="dict.type.device_status"
          :value="scope.row.deviceStatus"
        />
      </template>

      <template #planStatus="{row}">
        <el-tag :type="getOptionItem(planStatusOptions, row.planStatus).type">
          {{ getOptionItem(planStatusOptions, row.planStatus).label }}
        </el-tag>
      </template>

      <template #issuedStatus="{row}">
        <el-tag :type="getOptionItem(issuedStatusOptions, row.issuedStatus).type">
          {{ getOptionItem(issuedStatusOptions, row.issuedStatus).label }}
        </el-tag>
      </template>

    </u-page-config>

    <plan-detail-dialog
      v-if="visible"
      v-model="visible"
      :form="form"
    />

  </div>
</template>

<script>
import UPageConfig from '@/components/uPageConfig/index'
import UForm from '@/components/uForm'
import table from "@/mixin/uTable";
import {listManager} from "@/api/device/placeManager";
import {reqGetPlanList, reqStopUpdateSoftware, reqStopUpdatePolling} from "@/api/operationAndMonitoring/updatePlan";
import PlanDetailDialog from './components/planDetailDialog'

export default {
  name: "UpdatePlan",
  mixins: [table],
  dicts: ['device_status'],
  components: {UPageConfig, UForm, PlanDetailDialog},
  data() {
    return {
      // 下发状态 0未下发，1下发成功，-1下发失败
      issuedStatusOptions: [
        {label: '未下发', value: 0, type: 'primary'},
        {label: '下发成功', value: 1, type: 'success'},
        {label: '下发失败', value: -1, type: 'danger'},
      ],
      // 计划状态 0未下发，1下发成功，-1下发失败
      planStatusOptions: [
        {label: '新建', value: 0, type: 'primary'},
        {label: '执行成功', value: 1, type: 'success'},
        {label: '执行失败', value: -1, type: 'danger'},
        {label: '终止成功', value: 2, type: 'success'},
        {label: '终止失败', value: -2, type: 'danger'},
        {label: '部分成功', value: 3, type: 'warning'},
      ],
      filterArray: [
        {label: "设备ID", key: "deviceId", type: "input"},
        {label: "设备部署名称", key: "deploymentName", type: "input"},
        // {label: "设备型号", key: "deviceName", type: "input"},
        {label: "计划执行时间", key: "executionTime", type: "date"},
        {label: "下发状态", key: "issuedStatus", type: "select"},
        {label: "计划状态", key: "planStatus", type: "select"},
        {label: "计划创建时间", key: "createTime", type: "daterange", noRequestParams: true},
      ],
      tableColumn: [
        {label: "设备ID", prop: "deviceId"},
        {label: "设备部署名称", prop: "deploymentName"},
        {label: "设备状态", prop: "deviceStatus", type: 'slot', slot: 'deviceStatus'},
        {label: "计划状态", prop: "planStatus", type: 'slot', slot: 'planStatus'},
        {label: "下发状态", prop: "issuedStatus", type: 'slot', slot: 'issuedStatus'},
        {label: "计划执行时间", prop: "executionTime", type: 'time'},
        {
          label: "操作", type: "btn", attr: {width: 180}, btnArr: [
            {
              icon: "el-icon-view",
              text: "详细",
              emit: "rowDetail",
              permissions: 'operationAndMonitoring:updatePlan:detail'
            },
            {
              icon: "el-icon-video-pause",
              text: "终止计划",
              emit: "stopPlan",
              permissions: 'operationAndMonitoring:updatePlan:stop',
              // 计划状态新建并且下发成功才可以点击，其他禁用
              disabledRule: (row) => !(row.planStatus === 0 && row.issuedStatus === 1)
            }
          ]
        }
      ],
      actionBtn: [
        {
          type: 'primary',
          text: '创建更新计划',
          icon: 'el-icon-plus',
          emit: 'addPlan',
          permissions: 'operationAndMonitoring:updatePlan:add',
        },
        {
          type: 'success',
          text: '终止计划',
          icon: 'el-icon-video-pause',
          emit: 'stopPlan',
          permissions: 'operationAndMonitoring:updatePlan:stop',
          disabledRule: () => this.ids.length === 0
        }
      ],
      // 表单默认必填参数 重置表单时需要用到
      defaultForm: {
        deviceId: '',
        deploymentName: '',
        deploymentCode: '',
        operationUserCode: '',
        message: '',
        image: '',
        reportName: '',
        reportPhone: '',
      },
      formArray: [
        {
          label: "设备ID：", key: "deviceId", col: 24, slot: "deviceId",
          rule: {required: true, message: '设备ID不能为空！', trigger: 'blur'},
        },
        {label: "设备部署名称：", key: "deploymentName", col: 24, type: "input", attr: {disabled: true}},
        {
          label: "更新模块名称：", key: "moduleName", col: 24, type: "select", options: [],
          rule: {required: true, message: '运维人员不能为空！', trigger: 'change'},
        },
        {
          label: "计划执行时间：", key: "time", col: 24, type: "input",
          rule: {required: true, message: '问题描述不能为空！', trigger: 'blur'},
        },
        {label: "照片：", key: "image", col: 24, slot: "image"},
        {
          label: "报障人联系电话：", key: "reportName", col: 24, type: "input",
          rule: {required: true, message: '报障人联系电话不能为空！', trigger: 'blur'},
        },
        {
          label: "报障人姓名：", key: "reportPhone", col: 24, type: "input",
          rule: {required: true, message: '报障人姓名不能为空！', trigger: 'blur'},
        },
      ],
      // 查看详情表单配置
      detailArray: [
        {
          label: "设备ID：", key: "deviceId", col: 24, type: "text",
        },
        {label: "设备部署名称：", key: "deploymentName", col: 24, type: "text", placeholder: ' '},
        {
          label: "运维人员：", key: "operationUserCode", col: 24, type: "select", options: [],
        },
        {label: "问题描述：", key: "message", col: 24, type: "text", attr: {resize: 'none'}},
        {label: "照片：", key: "image", col: 24, type: "img"},
        {
          label: "报障人联系电话：", key: "reportPhone", col: 24, type: "text",
        },
        {
          label: "报障人姓名：", key: "reportName", col: 24, type: "text",
        },
      ],
      // 禁用表格前面多选框方法
      selectableFn: null,
      getStopPlanResultTimer: null
    };
  },
  methods: {
    // 获取选项数据
    getOptionItem(options, value, valueProps = 'value', labelProps = 'label') {
      return options.find(item => item[valueProps] === value) || {}
    },
    rowDetail(row) {
      this.form = row;
      this.visible = true;
    },
    // 添加
    addPlan() {
      this.$router.push({
        name: 'AddUpdatePlan'
      })
    },
    // 停止计划
    async stopPlan(row) {
      const ids = row ? [row.id] : this.ids;
      this.$confirm(`是否确定终止${row ? '当前行' : '已勾选'}的更新计划?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const selectedPlan = this.tableData.filter(item => ids.includes(item.id))
        const params = selectedPlan.map(item => {
          return {
            deviceId: item.deviceId,
            executionTime: item.executionTime,
            planId: item.planId
          }
        })
        if (params.length > 1) { //终止多个
          this.stopUpdateSoftware(params);
        } else { // 终止一个 需要获取messageCode 然后轮询获取结果
          this.getStopPlanMessageCodeAndPolling(params)
        }
      }).catch(() => {
      });
    },
    // @descriptions 获取messagecode并且轮询获取终止结果
    async getStopPlanMessageCodeAndPolling(params) {
      try {
        this.loading = true;
        const res = await reqStopUpdateSoftware(params)
        if (res.data) {
          // 30秒轮询获取结果
          if (this.getStopPlanResultTimer) return
          // 设置倒计时30秒
          this.getStopPlanResultDuration = 30
          this.getStopPlanResultTimer = setInterval(() => {
            // 倒计时30秒轮询获取终止结果
            if (this.getStopPlanResultDuration <= 0) {
              this.$modal.msgWarning("获取终止计划执行结果超时！")
              return this.clearStopPlanResultInterval()
            }
            this.getStopPlanResultDuration -= 3
            console.log('轮询终止结果倒计时', this.getStopPlanResultDuration)
            this.stopUpdatePolling(res.data)
          }, 3000)
        } else {
          this.loading = false;
          this.$modal.msgWarning("获取终止计划流水号messageCode失败！")
        }
      } catch (err) {
        this.loading = false;
        console.log("reqGetScreenshot 接口数据异常", err)
      }
    },
    // 清除获取截图轮询定时器
    clearStopPlanResultInterval() {
      clearInterval(this.getStopPlanResultTimer)
      this.getStopPlanResultTimer = null
      this.loading = false;
      this.getList()
    },
    /**
     获取终止更新计划结果
     */
    async stopUpdatePolling(messageCode) {
      try {
        const res = await reqStopUpdatePolling({
          messageCode
        })
        if(res.data !== null && res.data !== 0){
          const messageMap = {
            '1' : '终止计划执行成功',
            '-1' : '终止计划执行失败',
            '2' : '终止计划终止成功',
            '-2' : '终止计划终止失败',
            '3' : '终止计划部分成功'
          }
          this.loading = false;
          this.$modal.msgSuccess(messageMap[String(res.data)])
          this.clearStopPlanResultInterval()
        }
      } catch (err) {
        this.$modal.msgError('获取终止更新计划结果失败！')
        console.log("reqStopUpdatePolling 接口数据异常", err)
      }
    },
    /**
     终止计划详细
     */
    async stopUpdateSoftware(params) {
      try {
        this.loading = true;
        const res = await reqStopUpdateSoftware(params)
        // 终止多条计划 直接loading显示10秒钟
        setTimeout(() => {
          this.loading = false;
          this.$modal.msgSuccess('指令下发成功！')
          this.getList()
        }, 10000)
      } catch (err) {
        this.loading = false;
        this.$modal.msgError('终止更新计划失败！')
        console.log("reqStopUpdateSoftware 接口数据异常", err)
      }
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    /**
     * 重写请求参数
     * @function getList请求参数
     @return object getList请求参数对象
     * */
    getListRequestParams() {
      const params = {
        size: this.filter.pageSize,
        current: this.filter.pageNum,
        ...this.filter.data
      }
      if (this.filterArray) {
        this.filterArray.map(item => {
          // 判断哪些不是请求时需要的参数 一般daterang时间范围选择器参数都是不需要传给后端的，分成两个参数start和end
          if (item.noRequestParams) params[item.key] = null
        })
      }
      return params
    },
    /**
     * @function getInit 分页请求
     * @param request  分页请求函数
     * @param options  默认参数
     * */
    async getInit(request, options = {}) {
      let res = null
      if (request instanceof Function) {
        let params = this.getListRequestParams();
        // console.log(params, 'list請求參數')
        this.loading = true
        try {
          res = await request({
            ...params,
            ...options
          })
          this.tableData = res.records
          this.total = res.total
          return res
        } finally {
          this.loading = false
        }
      } else {
        res = request
      }
    },
    /** 查询工单列表 */
    getList() {
      this.getInit(reqGetPlanList, {})
    },
    /** 返回设备部署页面 */
    goBack() {
      this.$router.go(-1);
    },
  },
  created() {
    try {
      this.filterArray.find(item => item.key === 'issuedStatus').options = this.issuedStatusOptions;
      this.filterArray.find(item => item.key === 'planStatus').options = this.planStatusOptions;
    } catch (e) {
      console.log("找不到对应表单项", e)
    }


    // 计划状态为0前面多选框才可以选
    this.selectableFn = (row) => {
      return row.planStatus === 0 && row.issuedStatus === 1
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.query.updateList) vm.getList()
    })
  }
}
</script>

<style lang="scss" scoped>
.form-item-wrap {
  display: flex;
}
</style>
